import pymysql
from handle_conf import HandleConf
import logging

# 初始化日志记录配置
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

conf = HandleConf('conf.ini')


class DatabaseManager:
    def __init__(self):
        self.connection = None  # 初始化数据库连接为空

    def create_db_connection(self):
        """
        基于配置文件创建数据库连接。
        使用配置文件中指定的数据库配置信息
        """
        # 从配置文件读取数据库配置
        try:
            host = conf.get_value('sql', 'host')
            port = int(conf.get_value('sql', 'port'))
            user = conf.get_value('sql', 'user')
            password = conf.get_value('sql', 'password')
            database = conf.get_value('sql', 'database')
            charset = conf.get_value('sql', 'charset')

            # 验证端口号的合法性
            if not (1 <= port <= 65535):
                logging.error("Invalid port configuration.")
                raise ValueError("Invalid port configuration.")

            # 创建数据库连接
            self.connection = pymysql.connect(
                host=host,
                port=port,
                user=user,
                password=password,
                database=database,
                charset=charset
            )
        except Exception as e:
            logging.error(f"Failed to create database connection: {e}")
            raise

    def get_db(self, sql):
        """
        获取数据库，执行SQL查询并返回结果。

        参数:
        - sql: 字符串，要执行的SQL查询语句。

        返回值:
        - result: 查询结果，作为列表的元组。
        """
        if not self.connection:
            self.create_db_connection()  # 如果连接不存在，则创建连接

        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql)
                result = cursor.fetchall()
                return result
        except pymysql.Error as e:
            logging.error(f"Database operation failed: {e}")
            raise
        finally:
            if self.connection:
                self.connection.close()  # 无论成功或失败，最后都关闭数据库连接


# db_manager = DatabaseManager()
# result = db_manager.get_db("SELECT * FROM ;")
# print(result)
